package com.hcm.kernel.wechat;

import com.hcm.kernel.util.SystemConfig;
import com.hcm.kernel.wechat.util.HttpUtil;
import com.hcm.kernel.wechat.util.TokenCache;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.slf4j.LoggerFactory;

import java.nio.charset.UnsupportedCharsetException;

/**
 * Created by zhangzunwei on 15/5/27.
 */
public class MsgAPI {

    public static String send(String openid,String text){
        String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+ TokenCache.getAccessToken();
        if(SystemConfig.getBoolean("use_default_interface"))
            url = SystemConfig.getString("send_msg")+TokenCache.getAccessToken();

        //转为xml
        String json = "{\"touser\":\"%s\",\"msgtype\": \"text\",\"text\": { \"content\": \"%s\"}}";
        try {
            return HttpUtil.execute(url, new StringEntity(String.format(json, openid, text), "utf-8"));
        } catch (UnsupportedCharsetException e) {
            LoggerFactory.getLogger(MsgAPI.class).error("SendMsg error:{}", e.getMessage());
        }
        return "";
    }

    /**
     * 数据格式要看微信开发要求
     * @param json
     * @return
     */
    public static String send(String json){
        String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+ TokenCache.getAccessToken();
        if(SystemConfig.getBoolean("use_default_interface"))
            url = SystemConfig.getString("send_msg")+TokenCache.getAccessToken();

        ByteArrayEntity byteArrayEntity = new ByteArrayEntity(json.getBytes());
        return HttpUtil.execute(url, byteArrayEntity);
    }
}
